package com.example.fzj.hazelcast.shiro;

import com.hazelcast.core.HazelcastInstance;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.ServletContainerSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author fanzj
 * @Date 2021/8/15 3:37 下午
 * @Version 3.0
 * @Description
 */
@Slf4j
@Configuration
public class ShiroConfig {

    @Resource
    HazelcastInstance hazelcastInstance;

    // 路径过滤器
    private static Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
    // shiro 过程加过滤器
    private static Map<String, Filter> filters = new LinkedHashMap<>();

    /**
     * Title:
     * Description: 安全管理器
     * 
     * @return 
     * @date 2021/8/15-4:28 下午
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager() {
        log.info("注入Shiro的Web过滤器-->securityManager", ShiroFilterFactoryBean.class);
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置Realm，用于获取认证凭证
        securityManager.setRealm(new ShiroRealm());
        //注入session管理器
        securityManager.setSessionManager(sessionManager());
        //注入缓存管理器,CUSTOM
        securityManager.setCacheManager(new HazelcastCacheManager());
        return securityManager;
    }


    /**
     * Title:
     * Description: 
     * 
     * @return 
     * @date 2021/8/15-4:28 下午
     */
    @Bean("sessionManager")
    @Primary
    public ServletContainerSessionManager sessionManager(){
        ServletContainerSessionManager sessionManager = new ServletContainerSessionManager();
        return sessionManager;
    }

    /**
     * @return ShiroFilterFactoryBean
     * @Title: shiroFilter
     * @Description: TODO(shiro 过滤器)
     * @author 范再军
     * @date 2018年8月9日 上午11:12:02
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/");
        shiroFilterFactoryBean.setUnauthorizedUrl("/");
        shiroFilterFactoryBean.setSuccessUrl("/");
        shiroFilterFactoryBean.setFilters(filters);
        filterChainDefinitionMap.put("/**", "anon");
        filterChainDefinitionMap.put("/rest/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

}
